package com.dragonsky.shop.common.filter;

import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.*;
import org.apache.seata.core.context.RootContext;
import org.apache.seata.core.model.BranchType;

/**
 * Dubbo + Seata 集成:“branchType” is null异常
 * The type Transaction propagation consumer filter.
 * 重写dubbo-filter-seata,后续等dubbo-filter-seata修复了bug 可以删除
 *
 * https://blog.csdn.net/LilyVScarnation/article/details/143567051
 */
@Activate(group = {"consumer"})
public class SeataTransactionPropagationConsumerFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(SeataTransactionPropagationConsumerFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        LOGGER.info("SeataTransactionPropagationConsumerFilter-common inGlobalTransaction => {}", RootContext.inGlobalTransaction());
        if (RootContext.inGlobalTransaction()) {
            String xid = RootContext.getXID();
            BranchType branchType = RootContext.getBranchType();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Client side xid in RootContext[%s]", xid));
            }

            if (xid != null) {
                invocation.setAttachment("TX_XID", xid);
                if (branchType != null) {
                    invocation.setAttachment("TX_BRANCH_TYPE", branchType.name());
                }
            }
        }

        return invoker.invoke(invocation);
    }

}
